$(function () {
    // 点击注册
    $("#btn-login").on('click', function () {
        $('.login-box').hide()
        $('.reg-box').show()
    })
    // 点击登录
    $("#btn-reg").on('click', function () {
        $('.login-box').show()
        $('.reg-box').hide()
    })
    // 自定义规则
    layui.form.verify({
        pass: [
            /^[\S]{6,12}$/
            , '密码必须6到12位，且不能出现空格'
        ],
        repass: function (value) {
            let strPwd = $('.reg-box [name = password]').val().trim()
            if (strPwd !== value) {
                return '两次密码不一致'
            }
        }
    })
    // 提交数据
    $('#form_reg').on('submit', function (e) {
        e.preventDefault()
        const formData = {
            username: $('#form_reg input[name=username]').val().trim(),
            password: $('#form_reg input[name=password]').val().trim()
        }
        $.ajax({
            url: '/api/reguser',
            method: 'post',
            data: formData,
            success: (res) => {
                if (res.status !== 0) {
                    return layui.layer.msg(res.message)
                }
                layui.layer.msg('注册成功', {
                    icon: -1,
                    time: 1000
                }, () => {
                    $('#btn-reg').trigger('click')
                    this.reset()
                })
            }
        })
    })
    // 登录
    $('#form_login').on('submit', function (e) {
        e.preventDefault()
        const formData = {
            username: $('#form_login input[name=username]').val().trim(),
            password: $('#form_login input[name=password]').val().trim()
        }
        $.ajax({
            url: '/api/login',
            method: 'post',
            data: formData,
            success: (res) => {
                if (res.status !== 0) {
                    return layui.layer.msg(res.message)
                }
                layui.layer.msg('登录成功:)~~~', {
                    icon: -1,
                    time: 1000
                }, () => {
                    localStorage.setItem('token', res.token)
                    window.location.href = 'index.html'
                })
            }
        })
    })
})